package com.bonc.ioc.demo.config;

import com.alibaba.fastjson.JSON;
import com.bonc.ioc.common.util.AppReply;
import com.bonc.ioc.demo.exception.McpException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;

import java.io.IOException;

/**
 * * @description 用来实现捕获fegin调用的异常使用方式：
 * @FeignClient(value = "gsg-base-area", configuration = FeignExceptionConfiguration.class)
 *
 * @author jin.xu
 * @date 2020/12/1 17:59
 * @change: 2020/12/1 17:59 by jin.xu for init
 */
public class FeignExceptionConfiguration {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Bean
    public ErrorDecoder errorDecoder() {
        return new UserErrorDecoder();
    }

    /**
     * 重新实现feign的异常处理，捕捉restful接口返回的json格式的异常信息
     */
    public class UserErrorDecoder implements ErrorDecoder {

        @Override
        public Exception decode(String methodKey, Response response) {

            McpException exception = null;
            try {
                String json = Util.toString(response.body().asReader());

                if (StringUtils.isEmpty(json)) {
                    return null;
                }

                try {
                    AppReply appReply = JSON.parseObject(json, AppReply.class);
                    exception = new McpException(appReply.getMsg());
                } catch (Exception ex) {
                    exception = new McpException("Error:" + json);
                }


            } catch (IOException ex) {
                log.error(ex.getMessage(), ex);
                exception = new McpException(ex.getMessage());
            }
            return exception;
        }
    }
}